/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.oktago.ibore;

import android.content.Intent;
import android.text.Html;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.TextView;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.json.JSONArray;
import org.json.JSONException;

/**
 *
 * @author massimo
 */
public class ObjectListAdapter extends BaseAdapter implements OnItemClickListener {

    JSONArray data;
    ListActivity listActivity;

    public ObjectListAdapter(ListActivity listActivity) {
        data = new JSONArray();
        this.listActivity = listActivity;
    }

    @Override
    public int getCount() {
        return data.length();
    }

    @Override
    public Object getItem(int i) {
        try {
            return data.getJSONObject(i);
        } catch (JSONException ex) {
            Logger.getLogger(ObjectListAdapter.class.getName()).log(Level.SEVERE, null, ex);
        }
        return null;
    }

    @Override
    public long getItemId(int i) {
        try {
            int id = Integer.parseInt((String) data.getJSONObject(i).get("composite_instance"));
            return id;
        } catch (JSONException ex) {
            Logger.getLogger(ObjectListAdapter.class.getName()).log(Level.SEVERE, null, ex);
        }
        return 0;
    }

    public void updateDataSet(JSONArray data) {
        this.data = data;
    }

    public View getView(int i, View v, ViewGroup vg) {
        TextView textView = new TextView(listActivity);
        try {
            textView.setMinHeight(30);
            textView.setGravity(Gravity.CENTER_VERTICAL);
            textView.setText(Html.fromHtml(data.getJSONObject(i).getString("composite_instance_preview")));
        } catch (JSONException ex) {
            Logger.getLogger(ObjectListAdapter.class.getName()).log(Level.SEVERE, null, ex);
        }
        return textView;
    }

    public void onItemClick(AdapterView<?> parent, View v, int position, long id) {
        Intent i = new Intent(listActivity, DetailActivity.class);
        i.putExtra("id", id);
        listActivity.startActivity(i);
    }
}
